package com.opener.common.http;


import com.fasterxml.jackson.annotation.JsonIgnore;
import com.opener.common.model.Model;
import com.opener.common.utils.JsonUtils;

public class HttpResponse <T> extends Model {
	/**
	 * 
	 */
	private static final long serialVersionUID = 3027878830870620291L;
	private int status = StatusCode.SUCCESS;
	private String msg;
	private T data;
	public HttpResponse(){
		
	}
	public HttpResponse(String jsonString){
		T d = (T)JsonUtils.parse(jsonString);
		this.setData(d);
	}
	public HttpResponse(int status, String msg){
		this.status = status;
		this.msg = msg;
	}
	public HttpResponse(int status, String msg,Object data){
		this.status = status;
		this.msg = msg;
		this.data = (T)data;
	}
	
	public int getStatus() {
		return status;
	}

	public HttpResponse setStatus(int status) {
		this.status = status;
		return this;
	}

	public String getMsg() {
		return msg;
	}
	public HttpResponse setMsg(String msg) {
		this.msg = msg;
		return this;
	}
	
	public T getData() {
		return data;
	}

	public HttpResponse setData(T data) {
		this.data = data;
		return this;
	}

	@JsonIgnore
	public boolean isSuccess() {
		return this.status == StatusCode.SUCCESS;
	}
	
	@JsonIgnore
	public String getErrorMessage(){
		if(this.isSuccess()) {
			return null;
		}
		if(this.msg == null) {
			this.msg = "Server Error";
		}
		return this.msg;
	}
	
	public static HttpResponse<?> getErrorParamResponse(){
		HttpResponse<?> response = new HttpResponse<Object>();
		response.setStatus(StatusCode.ERROR_PARAM);
		response.setMsg("参数错误");
		
		return response;
	}
	public static HttpResponse<?> getSuccessResponse(){
		HttpResponse<?> response = new HttpResponse<Object>();
		response.setStatus(StatusCode.SUCCESS);
		response.setMsg("请求成功");
		return response;
	}
	public static HttpResponse<?> getFailureResponse(){
		HttpResponse<?> response = new HttpResponse<Object>();
		response.setStatus(StatusCode.ERROR);
		response.setMsg("操作失败");
		return response;
	}
}
